<?php
namespace App\Traits;
use App\Models\Member;

trait SubscribeMessage
{
    // 发送订阅消息
    public function sendSubscribe($_member_id,$_template_id,$_data,$_url = "")
    {
        $Wechat = $this->wechat();
        $_access_token = $Wechat->access_token->getToken();
        $_access_token = $_access_token["access_token"];
        $_data = array(
                "touser" => Member::where('id',$_member_id)->value('openid'),
                "template_id" => $_template_id,
                "data" => $_data,
                "page" => empty($_url) ? '' : $_url
            );
        $ch = curl_init();
        curl_setopt ( $ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token='.$_access_token);
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode($_data));
        $_response = curl_exec ( $ch );
        curl_close ( $ch );
        $_response = json_decode($_response,true);
        if($_response['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }
}
